<template>
  <div class="view-fill">
    <div
      v-if="!modifyInfo.visible && !templateModifyInfo.visible"
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        title="其他入库单明细"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="
              infoList.data.status !== 1 && $permission('otherStoreOrder:print')
            "
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <!-- <el-button
            v-if="
              infoList.data.status !== 1 && $permission('otherStoreOrder:print')
            "
            @click="print"
            >打印</el-button
          > -->
          <el-button
            v-if="
              infoList.data.status !== 1 &&
              $permission('otherStoreOrder:exportExcel')
            "
            @click="exportExcel"
            >导出excel</el-button
          >
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <el-button v-if="canPrintQrCode" @click="pringQrCode"
            >打印二维码</el-button
          >
          <el-button v-if="canSubmit" @click="submit">提交</el-button>
          <el-button v-if="canRevoke" @click="revoke">撤回</el-button>
          <el-button v-if="canExecute" @click="otherStore">入库</el-button>
          <el-button
            v-if="$permission('otherStoreOrder:saveCopeTemplate')"
            @click="saveCopeTemplate"
            >另存为模板</el-button
          >
        </template>

        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList">
              <template v-slot:basic-invoiceNumber>
                <div
                  v-if="
                    infoList.data.invoiceNumberList &&
                    infoList.data.invoiceNumberList.length > 0
                  "
                >
                  <span
                    v-for="(item, index) in infoList.data.invoiceNumberList"
                    :key="index"
                  >
                    <a v-if="index <= 1">{{ item }}</a>
                    <span
                      v-if="
                        index < 1 && infoList.data.invoiceNumberList.length > 1
                      "
                      >,</span
                    >
                  </span>
                  <el-dropdown
                    v-if="infoList.data.invoiceNumberList.length > 2"
                  >
                    <span class="el-dropdown-link">
                      更多
                      <i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-for="(item, index) in infoList.data
                            .invoiceNumberList"
                          :key="index"
                          >{{ item }}</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <span v-else>-</span>
              </template>
            </basic-information>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :check-box="false"
                :tab-index="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
              >
              </page-table>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <other-store-order-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :order-id="modifyInfo.orderId"
      @returnModify="refreshDetail"
    />
    <chose-printer :visible="printerInfo.visible" @callBack="printerCallBack" />
    <individual-details
      v-if="individualInfo.visible"
      v-model:show-dialog="individualInfo.visible"
      :query="individualInfo.query"
      :info="individualInfo.info"
      :page-status="canPrintQrCode"
    />
    <TemplateModify
      v-if="templateModifyInfo.visible"
      v-model:visible="templateModifyInfo.visible"
      :otherStoreOrderId="templateModifyInfo.otherStoreOrderId"
      :title="templateModifyInfo.title"
    />
  </div>
</template>

<script setup name="otherStoreOrderDetail">
import {
  otherStorePrintQrCode,
  otherStoreOrderDetailsPrintQrCodeVO,
  detailOtherStoreOrder,
  getOtherStoreOrderDetailCustomizeList,
  exportExcelOtherStoreOrder,
  getOtherStorePrint,
  submitOtherStoreOrder,
  executeOtherStoreOrder,
  revokeOtherStoreOrder,
} from '@/api/stock'
import { orderAffairAll } from '@/api/affair'
import { getCustomizeSetting } from '@/api/customize'
import { fatchTemplateByCode } from '@/api/base'
import OtherStoreOrderModify from './modify'
import IndividualDetails from './IndividualDetails'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const TemplateModify = defineAsyncComponent(() =>
  import('../otherTemplate/modify')
)

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'tableRow'])

const infoList = ref({
  data: {},
  fieldList: [
    { label: '入库单号', value: 'orderNo', type: 'text' },
    { label: '类型', value: 'typeValue', type: 'text' },
    { label: '入库仓库', value: 'depotName', type: 'text' },
    { label: '入库部门', value: 'deptName', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '入库人', value: 'storeUserName', type: 'text' },
    { label: '入库时间', value: 'storeTime', type: 'text' },
    { label: '出库方', value: 'otherSide', type: 'text' },
    { label: '出库方联系人', value: 'contact', type: 'text' },
    { label: '出库方电话', value: 'phone', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '更新人', value: 'updateUserName', type: 'text' },
    // { label: "发票号码", value: "invoiceNumber", type: "slot" },
    { label: '更新时间', value: 'updateTime', type: 'text' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'text',
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'text',
    },
    { label: '备注', value: 'remark', type: 'text' },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.tableRow.id,
      },
    },
    queryParams: {},
  },
})
//另存为模板参数
const templateModifyInfo = ref({
  visible: false,
  otherStoreOrderId: '',
  title: '另存为模板',
})
const modifyInfo = ref({
  visible: false,
  title: '',
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '打印二维码',
        event: printSingleQrCode,
        show: proxy.$permission('otherStoreOrder:printCode'),
        ifRender: ifRenderValue,
      },
      {
        label: '个体详情',
        event: showDetail,
        show: proxy.$permission('otherStoreOrder:IndividualDetails'),
      },
    ],
  },
})
const affairTableInfo = ref({
  query: {
    orderType: 5,
    orderId: props.tableRow.id,
    sort: 'operate_time desc',
  },
})
const individualInfo = ref({
  visible: false,
  query: {},
  info: {},
})
const printerInfo = ref({
  visible: false,
  data: {},
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canUpdate = computed(() => {
  return (
    proxy.$permission('otherStoreOrder:update') &&
    infoList.value.data.status === 1
  )
})
const canPrintQrCode = computed(() => {
  return (
    proxy.$permission('otherStoreOrder:printCode') &&
    (infoList.value.data.status === 2 || infoList.value.data.status === 3)
  )
})
const canSubmit = computed(() => {
  return (
    proxy.$permission('otherStoreOrder:submit') &&
    infoList.value.data.status === 1
  )
})
const canRevoke = computed(() => {
  return (
    proxy.$permission('otherStoreOrder:revoke') &&
    infoList.value.data.status === 2
  )
})
const canExecute = computed(() => {
  return (
    proxy.$permission('otherStoreOrder:store') &&
    infoList.value.data.status === 2
  )
})

setData()
function setData() {
  let obj = {
    price: {
      label: '单价',
      value: 'price',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('otherStoreOrder:price'),
      show: false,
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('otherStoreOrder:price'),
      show: false,
      hidden: true,
    },
    orderNo: {
      label: '单号',
      value: 'orderNo',
      componentType: 'input',
      show: false,
      type: 'column',
      hidden: true,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      permission: !proxy.$permission('otherStoreOrder:price'),
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
//另存为模板
function saveCopeTemplate() {
  templateModifyInfo.value.visible = true
  templateModifyInfo.value.otherStoreOrderId = props.tableRow.id
}
//提交
function submit() {
  let ids = []
  ids.push(infoList.value.data.id)
  submitOtherStoreOrder(ids).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
function revoke() {
  let ids = []
  ids.push(infoList.value.data.id)
  revokeOtherStoreOrder(ids).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
function otherStore() {
  let ids = []
  ids.push(infoList.value.data.id)
  executeOtherStoreOrder(ids).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
function refreshDetail() {
  getMain()
  getList()
}
function returnBack() {
  emits('returnBack', false)
}
function showDetail(row) {
  let ids
  if (row.groupConcatIds) {
    //未定义表示没有分组条件
    ids = row.groupConcatIds
  } else {
    ids = '' + row.id
  }
  individualInfo.value.query = {
    id: {
      queryType: 'IN',
      queryCategory: 'AND',
      value: ids,
    },
    orderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: props.tableRow.id,
    },
  }
  individualInfo.value.info = row
  individualInfo.value.visible = true
}
function getMain() {
  detailOtherStoreOrder(props.tableRow.id).then((resp) => {
    if (resp && resp.success) {
      infoList.value.data = resp.data
      infoList.value.data.invoiceNumberList = infoList.value.data.invoiceNumber
        ? infoList.value.data.invoiceNumber.indexOf(',') !== -1
          ? infoList.value.data.invoiceNumber.split(',')
          : [infoList.value.data.invoiceNumber]
        : []
    }
  })
}
function ifRenderValue() {
  return infoList.value.data.status === 2 || infoList.value.data.status === 3
}
function update() {
  modifyInfo.value.orderId = infoList.value.data.id
  modifyInfo.value.title = '修改入库单'
  modifyInfo.value.visible = true
}
function getList() {
  getOtherStoreOrderDetailCustomizeList(filterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.data = resp.data
    }
  })
}
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'otherStoreDetail',
    deptId: infoList.value.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            applicationId: props.tableRow.id,
            orderId: props.tableRow.id,
            orderNo: props.tableRow.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {},
        })
      }
    }
  })
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      applicationId: props.tableRow.id,
      orderId: props.tableRow.id,
      orderNo: props.tableRow.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {},
  })
  popoverVisible.value = false
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.value.data.orderNo,
      orderId: infoList.value.data.id,
      tempCode: 'otherStoreDetail',
      orderType: 5,
    })
  } catch (error) {}
}
function getPrintData(temp) {
  let params = {
    tableKey:
      'stockOtherStoreOrderDetail-com.slip.spd.entity.vo.stock.OtherStoreOrderDetailVO',
    orderIds: [props.tableRow.id],
  }
  getOtherStorePrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('otherStoreOrder:price')
      )
    }
  })
}
//导出excel
function exportExcel() {
  exportExcelOtherStoreOrder(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
//打印单个二维码
function printSingleQrCode(row = undefined) {
  if (!row.qrCode) {
    proxy.$message({
      message: '没有生成二维码，不能打印',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }

  let ids
  if (row.groupConcatIds) {
    //未定义表示没有分组条件
    ids = proxy.$fn.splitArr(row.groupConcatIds)
  } else {
    ids = [row.id]
  }
  if (ids.length > 0) {
    otherStoreOrderDetailsPrintQrCodeVO(ids).then((resp) => {
      if (resp && resp.success) {
        printerInfo.value.visible = true
        printerInfo.value.data = resp.data
      }
    })
  }
}
//打印整单的二维码
function pringQrCode() {
  let ids = []
  ids.push(props.tableRow.id)
  if (ids.length > 0) {
    otherStorePrintQrCode(ids).then((resp) => {
      if (resp && resp.success) {
        printerInfo.value.visible = true
        printerInfo.value.data = resp.data
      }
    })
  }
}
function printerCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.value.data, printer)
  }
  printerInfo.value.visible = false
}
function getCustomize() {
  let _tableInfo = tableInfo.value
  let param = {
    tableKey:
      'stockOtherStoreOrderDetail-com.slip.spd.entity.vo.stock.OtherStoreOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(_tableInfo.fieldList, data.detail, true)
      _tableInfo.fieldList = obj.fieldList
      getMain()
      getList()
    }
  })
}
</script>

<style scoped></style>
